<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<div th:replace="common/common::html"></div>
<head>
    <meta charset="UTF-8">
    <title th:text="#{user.page.title}"></title>
    <link th:href="@{/assets/css/page.css}" rel="stylesheet"/>
    <script th:inline="javascript">
        var _gridWidth;
        var _gridHeight;
        //页面自适应
        function resizePageSize(){
            _gridWidth = $(document).width()-12;/*  -189 是去掉左侧 菜单的宽度，   -12 是防止浏览器缩小页面 出现滚动条 恢复页面时  折行的问题 */
            _gridHeight = $(document).height()-65-40; /* -32 顶部主菜单高度，   -90 查询条件高度*/
        }

        $(function () {
            resizePageSize();
            var _columnWidth = (_gridWidth-150)/5;
            $("#flexigrid-id").flexigrid({
                width : _gridWidth,
                height : _gridHeight,
                url : /*[[@{/user/queryUserInfoListByPage}]]*/"",
                dataType : 'json',
                colModel : [
                    {display : 'userUuid',name : 'userUuid',width : 150,sortable : false,align : 'center',hide : 'true'},
                    {display : /*[[#{user.name}]]*/"",name : 'userName',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{user.nice.name}]]*/"",name : 'niceName',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{user.mobile}]]*/"",name : 'mobile',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{user.email}]]*/"",name : 'email',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{common.operation}]]*/"",name : 'userUuid',width : _columnWidth, sortable : true,align : 'center',process: function(v,_trid,_row) {
                            var html = '<div>'
                            html += `<a href="#" class="btn" onclick="modifyUserInfo('${v}')" title=[[#{common.modify}]]><i class="glyphicon glyphicon-pencil"></i></a>`
                            html += `<a href="#" class="btn" onclick="deleteUserInfo('${v}','${_row.niceName}')" title=[[#{common.delete}]]><i class="glyphicon glyphicon-trash"></i></a>`
                            html += `<a href="#" class="btn" onclick="allocateRole('${v}')" title=[[#{user.allocate.role}]]><i class="glyphicon glyphicon-share"></i></a>`
                            <!-- 添加单个用户重置密码按钮 -->
                            html += `<a href="#" class="btn" onclick="resetSinglePassword('${v}')" title=[[#{user.reset.pwd}]]><i class="glyphicon glyphicon-refresh"></i></a>`
                            html += '</div>'
                            return html;
                        }
                    },
                ],
                resizable : false, //resizable table是否可伸缩
                useRp : true,
                usepager : true, //是否分页
                autoload : false, //自动加载，即第一次发起ajax请求
                hideOnSubmit : true, //是否在回调时显示遮盖
                showcheckbox : true, //是否显示多选框
                rowhandler : rowDbclick, //是否启用行的扩展事情功能,在生成行时绑定事件，如双击，右键等
                rowbinddata : true
            });
            query()

            // 初始化修改用户对话框（原有代码）
            $("#modify-user-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{user.modify.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var flag = $("form#modify-user-form-id input.form-control").checkDom()
                            if(!flag){
                                return
                            }
                            $("#modify-user-form-id").submit()
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            })//end dialog

            // 修改用户表单提交（原有代码）
            $("#modify-user-form-id").ajaxForm({
                dataType: "json",
                success : function(data) {
                    message(data.msg);
                    query();
                    if (data.success){
                        $("#modify-user-dialog-id").dialog('close')
                    }
                },
                error : function() {
                    message(/*[[#{common.error}]]*/'');
                },
            })//end ajaxForm

            /**
             * 增加用户对话框（原有代码）
             */
            $("#add-user-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{user.add.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var flag = $("form#add-user-form-id input.form-control").checkDom()
                            if(!flag){
                                return
                            }
                            $("#add-user-form-id").submit()
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            })

            /**
             * 增加用户异步表单（原有代码）
             */
            $("#add-user-form-id").ajaxForm({
                dataType: "json",
                success : function(data) {
                    message(data.msg);
                    query();
                    if (data.success){
                        $("#add-user-dialog-id").dialog('close')
                    }
                },
                error : function() {
                    message(/*[[#{common.error}]]*/'');
                },
            })//end ajaxForm

            //删除用户对话框（原有代码）
            $("#delete-user-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{user.delete.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var ids = $("#delete-user-dialog-id").attr("ids")
                            $.ajax({
                                type: 'post',
                                async: false,
                                dataType : 'json',
                                url: /*[[@{/user/deleteUserByIds}]]*/'',
                                data: [{name:"ids",value:ids}],
                                success: function (data) {
                                    message(data.msg)
                                    if (data.success){
                                        $("#delete-user-dialog-id").dialog('close')
                                        query()
                                    }
                                },
                                error: function(msg){
                                    message(/*[[#{common.error}]]*/'');
                                }
                            });
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            });

            //分配角色对话框（原有代码）
            $("#allocate-role-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{user.allocat.role.dialog}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            let userUuidArray = $("#allocate-role-dialog-id").attr('ids')
                            let roleUuidArray = []
                            let treeObj = $.fn.zTree.getZTreeObj("allocate-role-ztree-id")
                            let nodes = treeObj.getCheckedNodes(true)
                            $(nodes).each(function (index,item) {
                                roleUuidArray.push(item.id)
                            })
                            $.ajax({
                                type: 'post',
                                async: false,
                                dataType : 'json',
                                url: /*[[@{/user/saveRoleRefUser}]]*/'',
                                data: [
                                    {name:"userUuidArray",value:userUuidArray},
                                    {name:"roleUuidArray",value:roleUuidArray},
                                ],
                                success: function (data) {
                                    message(data.msg)
                                    if (data.success){
                                        $("#allocate-role-dialog-id").dialog('close')
                                    }
                                },
                                error: function(msg){
                                    message(/*[[#{common.error}]]*/'');
                                }
                            });
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            })

            /**
             * 新增：密码重置对话框
             */
            $("#reset-pwd-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{user.reset.pwd}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var uuids = $("#reset-user-uuids").val();
                            $.ajax({
                                type: 'post',
                                async: false,
                                dataType : 'json',
                                url: /*[[@{/user/resetPassword}]]*/'',
                                data: [{name:"userUuids",value:uuids}],
                                success: function (data) {
                                    message(data.msg)
                                    if (data.success){
                                        $("#reset-pwd-dialog-id").dialog('close')
                                        query()
                                    }
                                },
                                error: function(msg){
                                    message(/*[[#{common.error}]]*/'');
                                }
                            });
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            });

        })//end ready function

        function query() {
            var userName = $("#user-name-id").val()
            var niceName = $("#user-nice-name-id").val()
            $("#flexigrid-id").flexOptions({
                extParam:[
                    {name:"userName",value:userName},
                    {name:"niceName",value:niceName}
                ]

            }).flexReload()
        }

        //双击事件（原有代码）
        function rowDbclick(r){
            $(r).dblclick(
                function() {
                    var columnsArray = $(r).attr('ch').split("_FG$SP_");
                    var userUuid = columnsArray[0]
                    modifyUserInfo(userUuid)
                });
        }

        //修改用户信息（原有代码）
        function modifyUserInfo(userUuid) {
            $.ajax({
                    type: 'post',
                    async: false,
                    dataType : 'json',
                    url: /*[[@{/user/queryUserInfoById}]]*/'',
                    data: [{name:"userUuid",value:userUuid}],
                    success: function (data) {
                        var list = $("form#modify-user-form-id input.form-control")
                        list.each(function (index,item) {
                            var name = $(item).attr("name")
                            $(this).val(data[name])
                        })

                        $("form#modify-user-form-id input.form-control").checkDom()
                        $("#modify-user-dialog-id").dialog('open')
                    },
                    error: function(msg){
                        message(/*[[#{common.error}]]*/'');
                    }
                }
            );
        }

        //增加用户（原有代码）
        function addUser() {
            $("form#add-user-form-id input.form-control").removeClass('ui-state-error');
            $("#add-user-form-id").resetForm();
            $("#add-user-dialog-id").dialog('open')
        }//end add user


        //删除用户（原有代码）
        function bathDeleteUser() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0)
            if(ids.length === 0){
                message(/*[[#{common.empty}]]*/'');
                return;
            }

            $("#delete-user-dialog-id").attr('ids',ids)
            var niceNameArray = $("#flexigrid-id").getFlexigridiAttrByIndex(4)
            $("#delete-user-list-id").text(niceNameArray.join(","))
            $("#delete-user-dialog-id").dialog('open')
        }

        //单独删除用户（原有代码）
        function deleteUserInfo(userUuid,niceName) {
            $("#delete-user-dialog-id").attr('ids',userUuid)
            $("#delete-user-list-id").text(niceName)
            $("#delete-user-dialog-id").dialog('open')
        }

        var allocateSetting = {
            check: {
                enable: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            }
        };

        //批量分配角色（原有代码）
        function bathAllocateRole() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0)
            if(ids.length === 0){
                message(/*[[#{common.empty}]]*/'');
                return;
            }
            allocateRole(ids)
        }

        //分配角色（原有代码）
        function allocateRole(userUuid) {
            $("#allocate-role-dialog-id").attr('ids',userUuid)
            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/user/queryRoleTreeListByUser}]]*/'',
                data: [{name:"userUuid",value:userUuid}],
                success: function (data) {
                    $.fn.zTree.init($('#allocate-role-ztree-id'),allocateSetting,data)
                    $("#allocate-role-dialog-id").dialog('open')
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }
            });
        }

        /**
         * 新增：单个用户密码重置
         */
        function resetSinglePassword(userUuid) {
            if (!userUuid) {
                message(/*[[#{common.empty}]]*/'');
                return;
            }
            $("#reset-user-uuids").val(userUuid);
            $("#reset-pwd-dialog-id").dialog('open');
        }

        /**
         * 新增：批量密码重置
         */
        function batchResetPassword() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0);
            if (ids.length === 0) {
                message(/*[[#{common.empty}]]*/'');
                return;
            }
            $("#reset-user-uuids").val(ids);
            $("#reset-pwd-dialog-id").dialog('open');
        }

    </script>

</head>
<body>
<header>
    <input id="user-name-id" th:placeholder="#{user.name.plc}">

    <input id="user-nice-name-id" th:placeholder="#{user.nice.name.plc}">

    <a href="#" class="btn-info btn" onclick="query()">
        <i class=" glyphicon glyphicon-search"></i>
        <span th:text="#{common.query}"></span>
    </a>

    <a href="#" class="btn-info btn" onclick="addUser()">
        <i class=" glyphicon glyphicon-plus"></i>
        <span th:text="#{common.add}"></span>
    </a>

    <a href="#" class="btn-info btn" onclick="bathDeleteUser()">
        <i class=" glyphicon glyphicon-trash"></i>
        <span th:text="#{common.delete}"></span>
    </a>

    <a href="#" class="btn-info btn" onclick="bathAllocateRole()">
        <i class=" glyphicon glyphicon-share"></i>
        <span th:text="#{user.allocate.role}"></span>
    </a>

    <!-- 新增：批量重置密码按钮 -->
    <a href="#" class="btn-info btn" onclick="batchResetPassword()">
        <i class=" glyphicon glyphicon-refresh"></i>
        <span th:text="#{user.batch.reset.pwd}"></span>
    </a>

</header>
<table id="flexigrid-id"></table>

<!-- 修改用户对话框（原有代码） -->
<div id="modify-user-dialog-id" style="display: none">
    <form id="modify-user-form-id" method="post" th:action="@{/user/modifyUserInfoById}">
        <div class="form-group" >
            <span th:text="#{user.uuid}"></span>
            <input class="form-control" name="userUuid" readonly>
        </div>

        <div class="form-group" >
            <span th:text="#{user.name}"></span>
            <input class="form-control" name="userName" pattern="^[a-z,A-Z,0-9]{4,}$">
        </div>

        <div class="form-group" >
            <span th:text="#{user.nice.name}"></span>
            <input class="form-control" name="niceName" pattern="^.+$">
        </div>

        <div class="form-group" >
            <span th:text="#{user.email}"></span>
            <input class="form-control" name="email" type="email" pattern="^[A-Za-z0-9]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$">
        </div>

        <div class="form-group" >
            <span th:text="#{user.mobile}"></span>
            <input class="form-control" name="mobile" type="number" pattern="^[0-9]{11}$">
        </div>
    </form>
</div>


<!-- 增加用户对话框（原有代码） -->
<div id="add-user-dialog-id" style="display: none">
    <form id="add-user-form-id" method="post" th:action="@{/user/addUserInfo}">

        <div class="form-group" >
            <span th:text="#{user.name}"></span>
            <input class="form-control" name="userName"
                   th:placeholder="#{user.name.plc}"
                   pattern="^[a-z,A-Z,0-9]{4,}$">
        </div>

        <div class="form-group" >
            <span th:text="#{login.user.password}"></span>
            <input class="form-control" name="password"
                   th:placeholder="#{user.password.plc}"
                   type="password" pattern="^.+$">
        </div>

        <div class="form-group" >
            <span th:text="#{user.nice.name}"></span>
            <input class="form-control" name="niceName"
                   th:placeholder="#{user.nice.name.plc}"
                   pattern="^.+$">
        </div>

        <div class="form-group" >
            <span th:text="#{user.email}"></span>
            <input class="form-control" name="email" type="email"
                   th:placeholder="#{user.email.plc}"
                   pattern="^[A-Za-z0-9]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$">
        </div>

        <div class="form-group" >
            <span th:text="#{user.mobile}"></span>
            <input class="form-control" name="mobile"
                   th:placeholder="#{user.modify.plc}"
                   type="number" pattern="^[0-9]{11}$">
        </div>
    </form>
</div>

<!-- 删除用户对话框（原有代码） -->
<div id="delete-user-dialog-id" style="display: none">
    <span id="delete-user-list-id"></span>
</div>

<!-- 分配角色对话框（原有代码） -->
<div id="allocate-role-dialog-id" style="display: none">
    <ul id='allocate-role-ztree-id' class="ztree"></ul>
</div>

<!-- 新增：密码重置对话框 -->
<div id="reset-pwd-dialog-id" style="display: none">
    <p th:text="#{user.reset.confirm}">确定要重置选中用户的密码吗？重置后密码将为空，用户登录时需重新设置。</p>
    <input type="hidden" id="reset-user-uuids" value="">
</div>
</body>
</html>
